<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类编码" prop="categoryCode">
        <el-input
          v-model="queryParams.categoryCode"
          placeholder="请输入分类编码"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入分类名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="categoryStatus">
        <el-select
          v-model="queryParams.categoryStatus"
          placeholder="分类状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['wms:itemCategory:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:itemCategory:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:itemCategory:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['wms:itemCategory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row :gutter="20">
      <!-- 分类树 -->
      <el-col :span="8" :xs="24">
        <div class="head-container">
          <el-input
            v-model="treeSearchValue"
            placeholder="请输入分类名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="tree-container">
          <el-tree
            :data="categoryTreeData"
            :props="{ label: 'categoryName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="categoryTreeRef"
            node-key="categoryId"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      
      <!-- 分类列表 -->
      <el-col :span="16" :xs="24">
        <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange" ref="categoryTableRef">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="分类ID" align="center" prop="categoryId" v-if="false" />
          <el-table-column label="分类编码" align="center" prop="categoryCode" />
          <el-table-column label="分类名称" align="center" prop="categoryName" />
          <el-table-column label="分类层级" align="center" prop="categoryLevel" />
          <el-table-column label="排序" align="center" prop="sortOrder" />
          <el-table-column label="状态" align="center" prop="categoryStatus">
            <template #default="scope">
              <dict-tag :options="statusOptions" :value="scope.row.categoryStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button
                type="text"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['wms:itemCategory:edit']"
              >修改</el-button>
              <el-button
                type="text"
                icon="Plus"
                @click="handleAdd(scope.row)"
                v-hasPermi="['wms:itemCategory:add']"
              >新增</el-button>
              <el-button
                type="text"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['wms:itemCategory:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改货品分类对话框 -->
    <el-dialog 
      :title="title" 
      v-model="open" 
      width="600px" 
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      destroy-on-close
      @close="cancel"
    >
      <el-form ref="categoryFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="父级分类" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="categoryTreeData"
            :props="{ value: 'categoryId', label: 'categoryName', children: 'children' }"
            value-key="categoryId"
            placeholder="不选择则创建为根节点分类"
            check-strictly
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="分类编码" prop="categoryCode">
          <el-input v-model="form.categoryCode" placeholder="请输入分类编码" />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="categoryStatus">
          <el-radio-group v-model="form.categoryStatus">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ItemCategory">
import { listItemCategory, treeListItemCategory, getItemCategory, addItemCategory, updateItemCategory, delItemCategory, changeItemCategoryStatus } from "@/api/wms/base/itemCategory";
import { getCurrentInstance, ref, watch, nextTick } from 'vue';

const { proxy } = getCurrentInstance();

// 分类状态选项
const statusOptions = ref([
  { label: '启用', value: '0' },
  { label: '禁用', value: '1' }
]);

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 货品分类表格数据
const categoryList = ref([]);
// 货品分类树数据
const categoryTreeData = ref([]);
// 树搜索值
const treeSearchValue = ref("");
// 当前选中的树节点
const currentNode = ref(null);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 表单参数
const form = ref({
  categoryId: null,
  parentId: null,
  categoryCode: null,
  categoryName: null,
  categoryLevel: null,
  categoryPath: null,
  isLeaf: true,
  sortOrder: 0,
  categoryStatus: "0",
  remark: null
});
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  parentId: null,
  categoryCode: null,
  categoryName: null,
  categoryStatus: null
});

// 表单校验
const rules = ref({
  parentId: [
    { required: false, message: "不选择将创建为根节点", trigger: "blur" }
  ],
  categoryCode: [
    { required: true, message: "分类编码不能为空", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9_-]{1,50}$/, message: '分类编码只能是字母、数字、下划线和中划线', trigger: 'blur' }
  ],
  categoryName: [
    { required: true, message: "分类名称不能为空", trigger: "blur" }
  ],
  sortOrder: [
    { required: true, message: "排序号不能为空", trigger: "blur" }
  ],
  categoryStatus: [
    { required: true, message: "状态不能为空", trigger: "change" }
  ]
});

/** 查询货品分类列表 */
function getList() {
  loading.value = true;
  listItemCategory(queryParams.value).then(response => {
    categoryList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询货品分类树结构 */
function getTreeList() {
  treeListItemCategory({}).then(response => {
    categoryTreeData.value = response.data;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    categoryId: null,
    parentId: currentNode.value ? currentNode.value.categoryId : null,
    categoryCode: null,
    categoryName: null,
    categoryLevel: null,
    categoryPath: null,
    isLeaf: true,
    sortOrder: 0,
    categoryStatus: "0",
    remark: null
  };
  
  // 重置表单验证
  nextTick(() => {
    if (proxy.$refs.categoryFormRef) {
      proxy.$refs.categoryFormRef.resetFields();
    }
  });
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryFormRef");
  if (proxy.$refs["categoryTreeRef"]) {
    proxy.$refs["categoryTreeRef"].setCurrentKey(undefined);
  }
  currentNode.value = null;
  queryParams.value.parentId = null;
  handleQuery();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.categoryId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  if (row != null && row.categoryId) {
    form.value.parentId = row.categoryId;
  }
  open.value = true;
  title.value = "添加货品分类";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const categoryId = row.categoryId || ids.value;
  getItemCategory(categoryId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改货品分类";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["categoryFormRef"].validate(valid => {
    if (valid) {
      // 处理根节点的情况
      if (!form.value.parentId) {
        form.value.parentId = 0; // 根节点的parentId设为0
        form.value.categoryLevel = 1; // 根节点层级为1
        form.value.categoryPath = form.value.categoryCode; // 根节点路径就是自己的编码
      }
      
      if (form.value.categoryId != null) {
        updateItemCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          getTreeList();
        });
      } else {
        addItemCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          getTreeList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const categoryIds = row.categoryId || ids.value;
  proxy.$modal.confirm('是否确认删除货品分类编号为"' + categoryIds + '"的数据项?').then(function() {
    return delItemCategory(categoryIds);
  }).then(() => {
    getList();
    getTreeList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "wms/itemCategory/export",
    {
      ...queryParams.value
    },
    `货品分类_${new Date().getTime()}.xlsx`
  );
}

/** 状态修改 */
function handleStatusChange(row) {
  let text = row.categoryStatus === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.categoryName + '"分类吗?').then(function() {
    return changeItemCategoryStatus({ categoryId: row.categoryId, categoryStatus: row.categoryStatus });
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function() {
    row.categoryStatus = row.categoryStatus === "0" ? "1" : "0";
  });
}

/** 过滤节点 */
function filterNode(value, data) {
  if (!value) return true;
  return data.categoryName.indexOf(value) !== -1;
}

/** 节点单击事件 */
function handleNodeClick(data) {
  currentNode.value = data;
  queryParams.value.parentId = data.categoryId;
  handleQuery();
}

/** 监听树搜索值变化 */
watch(treeSearchValue, (val) => {
  proxy.$refs["categoryTreeRef"].filter(val);
});

getList();
getTreeList();
</script>

<style scoped>
.tree-container {
  margin-top: 10px;
  background: #fff;
  border: 1px solid #e5e6e7;
  border-radius: 4px;
  padding: 10px;
  height: calc(100vh - 230px);
  overflow: auto;
}

.head-container {
  margin-bottom: 10px;
}
</style> 